<template>
  <div class="character-manage-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="flex items-center gap-4">
        <n-button
          text
          class="text-gray-600 hover:text-gray-900"
          @click="$router.back()"
        >
          <template #icon>
            <svg
              class="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M15 19l-7-7 7-7"
              ></path>
            </svg>
          </template>
          返回
        </n-button>
        <div>
          <h1 class="text-2xl font-bold text-gray-900">角色管理</h1>
          <p class="text-gray-600 mt-1">管理您的AI角色和对话历史</p>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <n-alert
      v-if="error"
      type="error"
      :title="error"
      closable
      class="mb-6"
      @close="clearError"
    />

    <!-- 当前选中的角色 -->
    <n-card v-if="currentCharacter" title="当前角色" class="mb-6">
      <div class="character-detail">
        <div class="character-header">
          <div class="character-avatar">
            <div class="avatar-placeholder">
              {{ currentCharacter.name.charAt(0) }}
            </div>
          </div>
          <div class="character-info">
            <h3 class="character-name">{{ currentCharacter.name }}</h3>
            <div class="character-personality">
              <n-tag
                v-for="trait in currentCharacter.personality"
                :key="trait"
                type="info"
                class="mr-2 mb-2"
              >
                {{ trait }}
              </n-tag>
            </div>
          </div>
          <div class="character-actions">
            <n-button type="primary" :loading="loading" @click="startNewChat">
              新对话
            </n-button>
            <n-button @click="showEditModal = true"> 编辑 </n-button>
            <n-button type="error" @click="showDeleteModal = true">
              删除
            </n-button>
          </div>
        </div>

        <div class="character-attributes">
          <div class="attribute-item">
            <h4 class="attribute-label">说话风格</h4>
            <p class="attribute-value">{{ currentCharacter.speakingStyle }}</p>
          </div>

          <div class="attribute-item">
            <h4 class="attribute-label">知识领域</h4>
            <p class="attribute-value">{{ currentCharacter.knowledgeBase }}</p>
          </div>

          <div class="attribute-item">
            <h4 class="attribute-label">故事背景</h4>
            <p class="attribute-value">{{ currentCharacter.background }}</p>
          </div>
        </div>
      </div>
    </n-card>

    <!-- 对话历史 -->
    <n-card title="对话历史">
      <div
        v-if="loading && currentCharacterConversations.length === 0"
        class="text-center py-8"
      >
        <n-spin size="large" />
        <p class="text-gray-500 mt-4">加载中...</p>
      </div>

      <div
        v-else-if="currentCharacterConversations.length === 0"
        class="empty-conversations"
      >
        <div class="text-center py-8">
          <svg
            class="w-12 h-12 text-gray-400 mx-auto mb-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-3.582 8-8 8a8.955 8.955 0 01-2.697-.413l-2.725.725.725-2.725A8.955 8.955 0 013 12c0-4.418 3.582-8 8-8s8 3.582 8 8z"
            ></path>
          </svg>
          <h3 class="text-lg font-medium text-gray-900 mb-2">暂无对话</h3>
          <p class="text-gray-500 mb-4">
            与{{ currentCharacter?.name }}开始您的第一次对话吧！
          </p>
          <n-button type="primary" :loading="loading" @click="startNewChat">
            开始对话
          </n-button>
        </div>
      </div>

      <div v-else class="conversations-list">
        <div
          v-for="conversation in currentCharacterConversations"
          :key="conversation.id"
          class="conversation-item"
        >
          <div class="conversation-info">
            <h4 class="conversation-title">
              {{ conversation.title || '未命名对话' }}
            </h4>
            <p class="conversation-time">
              {{ formatTime(conversation.updatedAt) }}
            </p>
          </div>

          <div class="conversation-actions">
            <n-button size="small" @click="continueChat(conversation)">
              继续对话
            </n-button>
            <n-button
              size="small"
              type="error"
              @click="confirmDeleteConversation(conversation)"
            >
              删除
            </n-button>
          </div>
        </div>
      </div>
    </n-card>

    <!-- 编辑角色模态框 -->
    <n-modal v-model:show="showEditModal">
      <n-card
        style="width: 600px"
        title="编辑角色"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <div class="edit-form">
          <n-form ref="editFormRef" :model="editForm" label-placement="top">
            <n-form-item label="角色名称">
              <n-input
                v-model:value="editForm.name"
                placeholder="输入角色名称"
              />
            </n-form-item>

            <n-form-item label="说话风格">
              <n-input
                v-model:value="editForm.speakingStyle"
                type="textarea"
                :rows="3"
                placeholder="描述角色的说话风格"
              />
            </n-form-item>

            <n-form-item label="知识领域">
              <n-input
                v-model:value="editForm.knowledgeBase"
                type="textarea"
                :rows="3"
                placeholder="描述角色的知识领域"
              />
            </n-form-item>
          </n-form>
        </div>

        <template #footer>
          <div class="flex justify-end gap-3">
            <n-button @click="showEditModal = false">取消</n-button>
            <n-button
              type="primary"
              :loading="loading"
              @click="saveCharacterEdit"
            >
              保存
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>

    <!-- 删除确认模态框 -->
    <n-modal v-model:show="showDeleteModal">
      <n-card
        style="width: 400px"
        title="确认删除"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <p class="text-gray-700">
          确定要删除角色 <strong>{{ currentCharacter?.name }}</strong> 吗？
        </p>
        <p class="text-sm text-gray-500 mt-2">
          删除后将无法恢复，所有相关对话也会被删除。
        </p>

        <template #footer>
          <div class="flex justify-end gap-3">
            <n-button @click="showDeleteModal = false">取消</n-button>
            <n-button
              type="error"
              :loading="loading"
              @click="confirmDeleteCharacter"
            >
              确认删除
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {
  NButton,
  NAlert,
  NCard,
  NTag,
  NSpin,
  NModal,
  NForm,
  NFormItem,
  NInput,
  useMessage,
  useDialog,
} from 'naive-ui';
import { useRoleplayStore } from '@/stores/roleplay';
import type { Character, Conversation } from '@/types/roleplay';

const router = useRouter();
const message = useMessage();
const dialog = useDialog();
const store = useRoleplayStore();

// 从store中获取状态和方法
const {
  currentCharacter,
  currentCharacterConversations,
  loading,
  error,
  createConversation,
  deleteCharacter,
  deleteConversation,
  clearError,
} = store;

// 本地状态
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const editForm = reactive({
  name: '',
  speakingStyle: '',
  knowledgeBase: '',
});

// 开始新对话
const startNewChat = async () => {
  if (!currentCharacter.value) return;

  try {
    const conversation = await createConversation(currentCharacter.value.id);
    router.push({
      name: 'Chat',
      params: {
        characterId: currentCharacter.value.id,
        conversationId: conversation.id,
      },
    });
  } catch (error) {
    console.error('创建对话失败:', error);
  }
};

// 继续对话
const continueChat = (conversation: Conversation) => {
  router.push({
    name: 'Chat',
    params: {
      characterId: conversation.characterId,
      conversationId: conversation.id,
    },
  });
};

// 保存角色编辑
const saveCharacterEdit = async () => {
  // TODO: 实现角色编辑功能
  message.info('角色编辑功能开发中...');
  showEditModal.value = false;
};

// 确认删除角色
const confirmDeleteCharacter = async () => {
  if (!currentCharacter.value) return;

  try {
    await deleteCharacter(currentCharacter.value.id);
    message.success('角色删除成功');
    showDeleteModal.value = false;
    router.push({ name: 'CharacterList' });
  } catch (error) {
    console.error('删除角色失败:', error);
  }
};

// 确认删除对话
const confirmDeleteConversation = (conversation: Conversation) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除对话"${conversation.title || '未命名对话'}"吗？`,
    positiveText: '确认',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await deleteConversation(conversation.id);
        message.success('对话删除成功');
      } catch (error) {
        console.error('删除对话失败:', error);
      }
    },
  });
};

// 格式化时间
const formatTime = (dateString: string) => {
  const date = new Date(dateString);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  if (diff < 60000) {
    return '刚刚';
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`;
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 初始化编辑表单
const initEditForm = () => {
  if (currentCharacter.value) {
    editForm.name = currentCharacter.value.name;
    editForm.speakingStyle = currentCharacter.value.speakingStyle;
    editForm.knowledgeBase = currentCharacter.value.knowledgeBase;
  }
};

onMounted(() => {
  if (!currentCharacter.value) {
    router.push({ name: 'CharacterList' });
    return;
  }
  initEditForm();
});
</script>

<style scoped>
@reference "@/styles/app.css";

.character-manage-page {
  @apply max-w-4xl mx-auto px-4 py-6;
}

.page-header {
  @apply mb-8;
}

.character-detail {
  @apply space-y-6;
}

.character-header {
  @apply flex items-start gap-4;
}

.character-avatar {
  @apply flex-shrink-0;
}

.avatar-placeholder {
  @apply w-16 h-16 bg-blue-500 text-white rounded-full flex items-center justify-center text-xl font-bold;
}

.character-info {
  @apply flex-1;
}

.character-name {
  @apply text-xl font-bold text-gray-900 mb-3;
}

.character-personality {
  @apply flex flex-wrap;
}

.character-actions {
  @apply flex gap-2 flex-shrink-0;
}

.character-attributes {
  @apply grid grid-cols-1 md:grid-cols-2 gap-4;
}

.attribute-item {
  @apply bg-gray-50 p-4 rounded-lg;
}

.attribute-label {
  @apply text-sm font-medium text-gray-700 mb-2;
}

.attribute-value {
  @apply text-gray-900;
}

.conversations-list {
  @apply space-y-3;
}

.conversation-item {
  @apply flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors;
}

.conversation-info {
  @apply flex-1;
}

.conversation-title {
  @apply font-medium text-gray-900;
}

.conversation-time {
  @apply text-sm text-gray-500 mt-1;
}

.conversation-actions {
  @apply flex gap-2;
}

.empty-conversations {
  @apply text-center py-8;
}

.edit-form {
  @apply space-y-4;
}
</style>
